package com.chinameyer.equipment_ebook.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chinameyer.equipment_ebook.bean.Event;
import com.chinameyer.equipment_ebook.bean.ManualType;
import com.chinameyer.equipment_ebook.mapper.EventMapper;
import com.chinameyer.equipment_ebook.mapper.ManualTypeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author meyer@HongYe
 */
@Service
public class ManualTypeService {

    @Autowired
    private ManualTypeMapper manualTypeMapper;
    @Autowired
    private EventMapper eventMapper;


    public boolean checkIsExistManualType(String manualType,Integer userId) {
        QueryWrapper<ManualType> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ManualType::getType,manualType).eq(ManualType::getUserId,userId);
        return this.manualTypeMapper.selectCount(wrapper) > 0;
    }

    @Transactional
    public void addManualType(String manualType,Integer userId) {
        ManualType manualTypeEntity = new ManualType();
        manualTypeEntity.setType(manualType);
        manualTypeEntity.setUserId(userId);
        this.manualTypeMapper.insert(manualTypeEntity);

        int typeId = manualTypeEntity.getId();
        List<String> equipmentNos = this.eventMapper.selectEquipmentNosByUserId(userId);
        for (String equipmentNo:equipmentNos) {
            Event event = new Event();
            event.setEquipmentNo(equipmentNo).setTypeId(typeId).setUserId(userId);
            this.eventMapper.insert(event);
        }
    }

    public boolean deleteManualType(Integer manualTypeId,Integer userId) {
        QueryWrapper<ManualType> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ManualType::getId,manualTypeId).eq(ManualType::getUserId,userId);
        return this.manualTypeMapper.delete(wrapper) > 0;
    }

    public boolean checkIsExistManualTypeExpectItself(Integer manualTypeId, String manualType, Integer userId) {
        QueryWrapper<ManualType> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ManualType::getType,manualType).ne(ManualType::getId,manualTypeId).eq(ManualType::getUserId,userId);
        return this.manualTypeMapper.selectCount(wrapper) > 0;
    }

    public boolean updateManualType(Integer manualTypeId, String manualType, Integer userId) {
        ManualType manualTypeEntity = new ManualType();
        manualTypeEntity.setType(manualType);
        manualTypeEntity.setId(manualTypeId);
        manualTypeEntity.setUserId(userId);
        return this.manualTypeMapper.updateById(manualTypeEntity) > 0;
    }

    public List<ManualType> getAllManualType(Integer userId) {
        QueryWrapper<ManualType> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ManualType::getUserId,userId);
        return this.manualTypeMapper.selectList(wrapper);
    }


}
